package com.wzapp.sitposture.common.base;

import com.wzapp.sitposture.common.util.HeaderUtil;
import com.wzapp.sitposture.common.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 功能: Endpoint的基类. <br/>
 *
 * @author ql
 * @date 2018-01-20 14:21
 * @since JDK 1.8
 */
@Slf4j
public class BaseEndpoint {

    private static final String TOKEN_HEADER_NAME = "access_token";

    /**
     * 客户端识别id前缀
     */
    private static final String TOKEN_CLIENT_ID_PREFIX = "oauth_";

    /**
     * 功能: 获取请求Header头信息 <br/>
     *
     * @return HeaderParam
     * @author ql
     * @date 2018-01-20 14:20
     */
    protected HeaderParam getHeaderParam() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HeaderParam headerParam = new HeaderParam();

        //todo 是否需要删除
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ToolUtil.isNotEmpty(token)) {
            headerParam.setToken(token);
            log.info("headerUtil token:" + token);
        }

        Principal principal = request.getUserPrincipal();
        if (null != principal) {
            if(!principal.getName().startsWith(TOKEN_CLIENT_ID_PREFIX)){
                headerParam.setUserId(principal.getName());
            }
            log.info("***** is {},userId:{}",principal.getName(), headerParam.getUserId());
        } else {
            log.info("Principal is NULL");
        }
        headerParam.setAuthorization(request.getHeader("Authorization"));
        headerParam.setClientInfo(request.getHeader("clientInfo"));
        HeaderUtil.getHeaderParam(request, headerParam);
        log.info("headerParam os:" + headerParam.getOs());

        DeviceInfo deviceInfo = HeaderUtil.getDeviceInfo(request);
        headerParam.setSignAppId(deviceInfo.getSignAppId());

        log.info("headerParam signAppId:" + headerParam.getSignAppId());
        return headerParam;
    }

    /**
     * 功能: 从TOKEN中提取用户ID <br/>
     *
     * @return java.lang.Long
     * @author ql
     * @date 2018-01-20 12:27
     */
    protected String getUserIdFromToken() {
        String userId = HeaderUtil.getUserIdFromPrincipal();
        if(ToolUtil.isNotEmpty(userId)){
            //如果客户端登录，返回null modify by ql 2018/10/24
            if(userId.startsWith(TOKEN_CLIENT_ID_PREFIX)){
                userId = null;
            }
        }
        log.info("headerParam userId:" + userId);
        return userId;
    }
}
